package cn.mybatishelper.entity.mybatis;

import cn.mybatishelper.entity.database.ColumnEntity;
import cn.mybatishelper.entity.database.DatabaseEntity;

/**
 * 结果类型元素，即<resultMap id="xxx"/>类型元素 
 * @author yao
 *
 */
public class ResultMapElement extends MybatisElement {
	/** 元素的标签，在此为resultMap类型 **/
	private final String type="resultMap";
	
	public ResultMapElement(){
		super("BaseResultMap", null, false);
	}

	public ResultMapElement(String id, DatabaseEntity databaseEntity, boolean isMethod) {
		super(id, databaseEntity, isMethod);
	}

	@Override
	public String toXmlString() {
		if(!validateDatabaseEntity()){
			return null;
		}
		
		if(!validateElement()){
			return null;
		}
		
		StringBuilder xmlStrBuffer = new StringBuilder("\n");
		xmlStrBuffer.append("\t");
		xmlStrBuffer.append("<resultMap id='"+this.id+"' type='"+databaseEntity.getJavaPackageName()+"."+databaseEntity.getObjectName()+"'>");
		for(ColumnEntity column : databaseEntity.getColumnList()){
			xmlStrBuffer.append("\n");
			xmlStrBuffer.append("\t\t");
			xmlStrBuffer.append("<result column='"+column.getColumnName()+"' property='"+column.getPropertyName()+"'/>");
		}
		xmlStrBuffer.append("\n");
		xmlStrBuffer.append("\t");
		xmlStrBuffer.append("</resultMap>");

		String xmlString = xmlStrBuffer.toString();
		return xmlString;
	}
	
	public String toCodeString() {
		if (!validateDatabaseEntity()) {
			return null;
		}
		
		StringBuilder propertyStr = new StringBuilder();
		StringBuilder getSetStr = new StringBuilder();
		for(ColumnEntity column : databaseEntity.getColumnList()){
			propertyStr.append("\n");
			propertyStr.append("\t");
			propertyStr.append("private "+column.getJavaType()+" "+column.getPropertyName()+";");
			
			String property = column.getPropertyName();
			property = property.replaceFirst(property.substring(0, 1),property.substring(0, 1).toUpperCase());
			getSetStr.append("\n");
			getSetStr.append("\t");
			getSetStr.append("public "+column.getJavaType()+" get"+property+"() {");
			getSetStr.append("\n\t\t");
			getSetStr.append("return "+column.getPropertyName()+";");
			getSetStr.append("\n\t");
			getSetStr.append("}");
			getSetStr.append("\n");
			getSetStr.append("\t");
			getSetStr.append("public void set"+property+"("+column.getJavaType()+" "+column.getPropertyName()+") {");
			getSetStr.append("\n\t\t");
			getSetStr.append("this."+column.getPropertyName()+" = "+column.getPropertyName()+";");
			getSetStr.append("\n\t");
			getSetStr.append("}");
		}
		
		String result = propertyStr.toString()+"\n\n"+getSetStr.toString();
		return result;
	}

	
	/******************************get/set方法*************************************/
	public String getType() {
		return type;
	}

}
